package com.turbo.cloud.gateway.web.webservice;

import com.turbo.cloud.gateway.api.R;
import com.turbo.cloud.gateway.api.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zhangluning
 */
@Slf4j
@RefreshScope
@RequiredArgsConstructor
@RestController
public class GatewayWebservice {

    final DiscoveryClient discoveryClient;

    final WebClient webClient;

    @GetMapping(value = "/webservice/all-micro-service/initApis")
    public Mono<List<Result<Boolean>>> initApis() {
        List<String> serviceIds = discoveryClient.getServices();
        //
        //String serviceId = "turbo-cloud-ums";
        //String initApiPath = "http://" + serviceId + "/interface/api/initApi";
        //return webClient.get().uri(initApiPath)
        //        .retrieve().bodyToMono(Boolean.class).then(Mono.just(serviceIds));

        return Flux.fromIterable(serviceIds).flatMap(serviceId -> {
            String initApiPath = "http://" + serviceId + "/interface/api/initApi";
            return webClient.get().uri(initApiPath)
                    .retrieve().bodyToMono(new ParameterizedTypeReference<Result<Boolean>>(){
                    }).log().onErrorReturn((e) -> {
                        log.error("{} initApis error:", serviceId, e);
                        return true;
                    }, R.result(false));
        }).collectList();
    }
}
